package cn.baddonkey.photography.agent.utils;

import cn.baddonkey.photography.agent.core.PageData;
import cn.baddonkey.photography.agent.core.constants.CommonConstants;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class PageUtils {

    public static <D> PageData<D> getPageData(List<?> list, long total, Class<D> target) {
        List<D> targetList = ConvertUtils.sourceToTarget(list, target);

        return new PageData<>(targetList, total);
    }

    public static <D> PageData<D> getPageData(IPage<?> page, Class<D> target) {
        return getPageData(page.getRecords(), page.getTotal(), target);
    }

    public static <T> IPage<T> getPage(
            Map<String, Object> params, String defaultOrderField, boolean isAsc) {
        // 分页参数
        long curPage = 1;
        long limit = 10;

        if (params.get(CommonConstants.PAGE) != null) {
            curPage = Long.parseLong((String) params.get(CommonConstants.PAGE));
        }
        if (params.get(CommonConstants.LIMIT) != null) {
            limit = Long.parseLong((String) params.get(CommonConstants.LIMIT));
        }

        // 分页对象
        Page<T> page = new Page<>(curPage, limit);

        // 分页参数
        params.put(CommonConstants.PAGE, page);

        // 排序字段
        Object orderField = params.get(CommonConstants.ORDER_FIELD);
        String order = (String) params.get(CommonConstants.ORDER);

        List<String> orderFields = new ArrayList<>();

        // 处理排序字段
        if (orderField instanceof String) {
            orderFields.add((String) orderField);
        } else if (orderField instanceof List) {
            orderFields.addAll((List<String>) orderField);
        }

        // 有排序字段则排序
        if (CollectionUtils.isNotEmpty(orderFields)) {
            if (StringUtils.isNotBlank(order) && CommonConstants.ASC.equalsIgnoreCase(order)) {
                return page.addOrder(OrderItem.ascs(orderFields.toArray(new String[0])));
            } else {
                return page.addOrder(OrderItem.descs(orderFields.toArray(new String[0])));
            }
        }

        // 没有排序字段，使用默认排序
        if (StringUtils.isNotBlank(defaultOrderField)) {
            if (isAsc) {
                page.addOrder(OrderItem.asc(defaultOrderField));
            } else {
                page.addOrder(OrderItem.desc(defaultOrderField));
            }
        }

        return page;
    }
}
